package com.niiwoo.civet.trade.service.local.contract;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.dao.entity.FadadaContractTemplateFile;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectContract;
import com.niiwoo.civet.user.dto.request.SimpleOrgInfo;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO.DynamicTable;
import com.niiwoo.tripod.fadada.dto.response.FadadaResponseDTO;
import com.niiwoo.tripod.fadada.enums.SignClientRoleEnum;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 企业代扣合同
 *
 * @author liaojunjun
 */
@Service
public class CompanyWithhold extends AbstractFadadaContract {

    private static final Logger logger = LoggerFactory.getLogger(CompanyWithhold.class);

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Reference(version = "1.0.0")
    private OrganizationDubboService organizationDubboService;

    @Autowired
    private PrivacyMasks privacyMasks;

    @Override
    public ProjectContract contractHandler(FadadaContractTemplateFile contractTemplate, String bizContractNo,
                                           Project project, String userId) throws Exception {
        logger.info("企业代扣合同处理开始... projectId:{}", project.getProjectId());
        String contractId = snowflakeIdWorker.nextId() + "";

        SimpleOrgInfo orgInfoRespDTO = organizationDubboService.getByOrgId(userId);
        this.generateContract(contractTemplate, contractId, orgInfoRespDTO, project.getProjectId());

        ProjectContract result = this.signContract(contractTemplate.getTemplateId(), contractId, orgInfoRespDTO, project);

        this.contractFilling(contractId);
        logger.info("企业代扣合同处理结束... projectId:{}", project.getProjectId());
        return result;
    }

    private void generateContract(FadadaContractTemplateFile contractTemplate, String contractId, SimpleOrgInfo orgInfoRespDTO, Long projectId) throws Exception {
        logger.info("企业代扣合同生成开始... projectId:{}", projectId);
        Map<String, String> contractContentMap = new HashMap<>();
        contractContentMap.put("userId", orgInfoRespDTO.getId());
        contractContentMap.put("idCard", StringUtils.isNoneBlank(orgInfoRespDTO.getLegalPersonCertNumber()) ? privacyMasks.decryptPrivacy(orgInfoRespDTO.getLegalPersonCertNumber()) : "");
        contractContentMap.put("name", orgInfoRespDTO.getOrganizationName());
        contractContentMap.put("mobileNo", StringUtils.isNoneBlank(orgInfoRespDTO.getLegalPersonPhoneNumber()) ? privacyMasks.decryptPrivacy(orgInfoRespDTO.getLegalPersonPhoneNumber()) : "");
        contractContentMap.put("domainName", "www.niiwoo.com");//域名
        contractContentMap.put("platformName", "你我金融");//平台名
        contractContentMap.put("contractNo", contractId);
        contractContentMap.put("sinDate", FastDateFormat.getInstance("yyyy年MM月dd日").format(new Date()));

        GenerateContractRequestDTO dto = new GenerateContractRequestDTO();
        dto.setContractId(contractId);
        dto.setDocTitle(contractTemplate.getTemplateName());
        dto.setTemplateId(contractTemplate.getTemplateId());
        dto.setParameterMap(contractContentMap);

        // 签章列表
        List<List<String>> signatureNamesList = new ArrayList<>();

        // 签章信息
        String antiGuaranteeSignatureNamesText = "                授权人（签章）：" + orgInfoRespDTO.getOrganizationName();
        List<String> antiGuaranteeSignatureNamesCells = new ArrayList<>();
        antiGuaranteeSignatureNamesCells.add(antiGuaranteeSignatureNamesText);
        signatureNamesList.add(antiGuaranteeSignatureNamesCells);

        List<String> headers = new ArrayList<>();
        headers.add("");
        // 所有人签名 在pdf合同模板的keyword下面插入(正好在页尾，不用留空白)，需要留够空白，不然会覆盖下面的内容
        DynamicTable signNameTable = new DynamicTable();
        signNameTable.setInsertWay(1);
        signNameTable.setKeyword("身份证号码");
        signNameTable.setCellHeight(60f);
        signNameTable.setHeaders(headers);
        // 签名时需要增加高度并居中显示
        signNameTable.setCellVerticalAlignment(5);
        signNameTable.setDatas(signatureNamesList);
        signNameTable.setBorderFlag(false);
        List<DynamicTable> tables = new ArrayList<DynamicTable>();
        tables.add(signNameTable);

        dto.setDynamicTables(tables);

        generateContract(dto);
        logger.info("企业代扣合同生成结束... projectId:{}", projectId);
    }

    private ProjectContract signContract(String templateId, String contractId, SimpleOrgInfo orgInfoRespDTO,
                                         Project project) throws Exception {
        String METHOD_NAME = "法大大合同自动签署-企业代扣 projectId:" + project.getProjectId();
        logger.info(METHOD_NAME);

        String docTitle = project.getBorrowUserName() + "的代扣合同_" + contractId;

        // 代扣人签署
        String transactionId = snowflakeIdWorker.nextId() + "";
        String caCertId = orgInfoRespDTO.getFadadaCacertId();
        String signKeyword =  "      授权人（签章）：" + orgInfoRespDTO.getOrganizationName();
        FadadaResponseDTO fadadaResponse = extSignAuto(transactionId, contractId, caCertId,
                SignClientRoleEnum.BORROWER.getValue(), docTitle, signKeyword);
        logger.info("法大大合同自动签署-企业代扣 代扣人签署结束... projectId:{}", project.getProjectId());
        return this.buildContractUpdateRecord(templateId, contractId, transactionId,
                fadadaResponse.getViewUrl(), fadadaResponse.getDownloadUrl());
    }
}
